package com.ict.luxshare.bt_demo;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class BtReceiver extends BroadcastReceiver {
    private final static String TAG = "jb:BtReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            switch(state) {
                case BluetoothAdapter.STATE_OFF:
                    Toast.makeText(context, "Bluetooth off", Toast.LENGTH_LONG).show();
                    Log.d(TAG, "STATE_OFF()");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d(TAG, "STATE_TURNING_OFF()");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Toast.makeText(context, "Bluetooth on", Toast.LENGTH_LONG).show();
                    Log.d(TAG, "STATE_ON()");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.d(TAG, "STATE_TURNING_ON()");
                    break;
            }

        }
        else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
            int blueconState = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 0);
            switch (blueconState) {
                case BluetoothAdapter.STATE_CONNECTED:
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    String bt_Name = device.getName();

                    if (bt_Name.equals("LuxShare-ICT")) {
                        Intent PopIntent = new Intent(context, PopupActivity.class);
                        context.startActivity(PopIntent);
                        Log.d(TAG, "STATE_CONNECTED");
                    } else {
                        Toast.makeText(context, "It's not LuxShare headset!", Toast.LENGTH_LONG).show();
                        Log.d(TAG, "Not LuxShare headset connected.");
                    }
                    break;
                case BluetoothAdapter.STATE_CONNECTING:
                    Log.i(TAG, "STATE_CONNECTING");
                    break;
                case BluetoothAdapter.STATE_DISCONNECTED:
                    Log.i(TAG, "STATE_DISCONNECTED");
                    break;
                case BluetoothAdapter.STATE_DISCONNECTING:
                    Log.i(TAG, "STATE_DISCONNECTING");
                    break;
                default:
                    break;
            }
        }
    }
}
